import RPi.GPIO as GPIO
from time import sleep
import paho.mqtt.client as mqtt

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe("#")


client = mqtt.Client()

GPIO.setmode(GPIO.BOARD)
outputPinG=40
outputPinY=38
outputPinR=36

GPIO.setup(outputPinG,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.output(outputPinG,0)

GPIO.setup(outputPinY,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.output(outputPinY,0)

GPIO.setup(outputPinR,GPIO.OUT)
GPIO.setwarnings(False)
GPIO.output(outputPinR,0)

last_word=0

while 1:
    with open('/home/max/multimedia/meter.log', 'r') as file:
        try:
            last_line = file.readlines()[-1]
            last_word = last_line.split()[-1]
            print("reading...")
        except:
            pass

        try:
            client.username_pw_set("", "")
            client.connect("", 1883, 60)
            client.publish("pc/noize",last_word)
        except:
            pass

        if int(last_word) <10:
            print("<10")
            sleep(1)
        if int(last_word) >=10 and int(last_word) < 20:
            print(">10")
            GPIO.output(outputPinG,1)
            sleep(500 / 1000)
            GPIO.output(outputPinG,0)
            sleep(500 / 1000)


        if int(last_word) >=20 and int(last_word) < 30:
            print(">20")
            GPIO.output(outputPinY,1)
            sleep(500 / 1000)
            GPIO.output(outputPinY,0)
            sleep(500 / 1000)

        if int(last_word) >=30 and int(last_word) < 40:
            print(">30")
            GPIO.output(outputPinR,1)
            sleep(500 / 1000)
            GPIO.output(outputPinR,0)
            sleep(500 / 1000)

        if int(last_word) >=40:
            print(">40")
            GPIO.output(outputPinR,1)
            sleep(100 / 1000)
            GPIO.output(outputPinR,0)
            sleep(100 / 1000)

